﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Common
{
    /// <summary>
    /// JWT帮助
    /// </summary>
    public class JWTHelper
    {
        /// <summary>
        /// 配置
        /// </summary>
        private readonly IConfiguration _configuration;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public JWTHelper(IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            _configuration = configuration;
            _httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 生成JwtToken
        /// </summary>
        /// <param name="jsonString"></param>
        /// <param name="roleList"></param>
        /// <param name="minutes"></param>
        /// <returns></returns>
        public string GenerateJwtToken(string jsonString, List<string> roleList, int minutes = 60)
        {
            Claim[] claim = new Claim[]
            {
                new Claim(ClaimTypes.UserData,jsonString),
                new Claim(ClaimTypes.Role,string.Join(",",roleList))
            };
            byte[] secretBytes = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
            SymmetricSecurityKey key = new(secretBytes);
            SigningCredentials credentials = new(key, SecurityAlgorithms.HmacSha256);
            DateTime now = DateTime.Now;
            JwtSecurityToken token = new(
                issuer: _configuration["Authentication:Issuer"],
                audience: _configuration["Authentication:Audience"],
                claims: claim,
                notBefore: now,
                expires: now.AddMinutes(minutes),
                signingCredentials: credentials);
            string tokenString = new JwtSecurityTokenHandler().WriteToken(token);
            return tokenString;
        }
        /// <summary>
        /// 解密Token
        /// </summary>
        /// <param name="token"></param>
        /// <param name="claimType"></param>
        /// <returns></returns>
        public string TokenDecrypt(string? token,string? claimType)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(claimType))
                {
                    token = _httpContextAccessor.HttpContext?.Request.Headers["Authorization"];
                    if (string.IsNullOrWhiteSpace(token))
                    {
                        return "";
                    }
                }
                token = token.Replace("Bearer ", "");
                 var jstHandler = new JwtSecurityTokenHandler();
                var jst = jstHandler.ReadJwtToken(token);
                Claim? claim = jst.Claims.FirstOrDefault(x => x.Type == claimType);
                if (claim == null)
                {
                    return "";
                }
                return claim.Value;
            }
            catch
            {
                return "";
            }
        }
    }
}
